<template>
  <div class="log-container">
    <div class="search-bar">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="登录人">
          <el-input
            v-model="searchForm.userName"
            placeholder="请输入登录人姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="searchForm.startDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchLogs">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="logList"
      stripe
      style="width: 100%"
      empty-text="暂无数据">
      <el-table-column label="序号" width="80">
        <template #default="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="登录人姓名" prop="userName" width="120" />
      <el-table-column label="用户类型" prop="userType" width="120">
        <template #default="scope">
          {{ scope.row.isAdmin === 1 ? '管理员' : '普通用户' }}
        </template>
      </el-table-column>
      <el-table-column label="登录内容" prop="logContent" />
      <el-table-column label="IP地址" prop="ipAddress" width="150" />
      <el-table-column label="操作系统" prop="os" width="120" />
      <el-table-column label="浏览器" prop="ie" width="120" />
      <el-table-column label="登录时间" prop="createTime" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchForm: {
        userName: "",
        startDate: null,
      },
      logList: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
    };
  },
  methods: {
    fetchLogs() {
      const { userName, startDate } = this.searchForm;
      this.$axios
        .get("http://localhost:8080/log/search", {
          params: {
            userName,
            startDate,
            page: this.currentPage,
            size: this.pageSize,
          },
        })
        .then((response) => {
          const { data } = response;
          if (data && data.list) {
            this.logList = data.list;
            this.total = data.total;
          } else {
            this.logList = [];
            this.total = 0;
          }
        })
        .catch((error) => {
          console.error("日志查询失败", error);
          this.$message.error("日志查询失败");
        });
    },
    formatDate(date) {
      if (!date) return "";
      const d = new Date(date);
      const pad = n => n.toString().padStart(2, '0');
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.fetchLogs();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchLogs();
    },
    recordLoginLog(user, userAgent, ipAddress) {
      const userType = user.isAdmin === 1 ? "管理员" : "普通用户";
      const logData = {
        userID: user.userId,
        userName: user.userName, // 确保后端支持这个字段
        isAdmin: user.isAdmin, // 新增字段，用于存储用户类型
        logContent: `${userType}登录系统`, // 修改日志内容
        ipAddress,
        os: this.getOS(userAgent),
        ie: this.getBrowser(userAgent),
        createTime: new Date().toISOString(),
      };
      this.$axios.post("http://localhost:8080/log/insert", logData).catch((error) => {
        console.error("登录日志记录失败", error);
      });
    },
    getOS(userAgent) {
      if (userAgent.includes("Windows")) {
        return "Windows";
      } else if (userAgent.includes("Linux")) {
        return "Linux";
      } else if (userAgent.includes("Mac OS")) {
        return "macOS";
      }
      return "未知操作系统";
    },
    getBrowser(userAgent) {
      if (userAgent.includes("Chrome")) {
        return "Chrome";
      } else if (userAgent.includes("Firefox")) {
        return "Firefox";
      } else if (userAgent.includes("Safari")) {
        return "Safari";
      } else if (userAgent.includes("Edge")) {
        return "Edge";
      }
      return "未知浏览器";
    },
  },
  mounted() {
    this.fetchLogs();
  },
};
</script>

<style scoped>
.log-container {
  padding: 32px 24px;
  background: #f7f8fa;
  min-height: 100vh;
}

.search-bar {
  margin-bottom: 24px;
  background: #fff;
  padding: 18px 24px 8px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
}

.el-form-item {
  margin-right: 24px;
}

.el-table {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
  margin-bottom: 24px;
}

.el-table th {
  background: #f0f2f5;
  color: #333;
  font-weight: 600;
}

.el-table td {
  color: #555;
}

.el-pagination {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 900px) {
  .log-container {
    padding: 12px 4px;
  }
  .search-bar {
    padding: 10px 6px 2px 6px;
  }
}
</style>